package com.example.esp8266.Equipment.Task_Fragment;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.esp8266.Equipment.Fragment_CallBack;
import com.example.esp8266.Init.ESP8266_APP;
import com.example.esp8266.Library.RoomLib.AppDatabase;
import com.example.esp8266.Library.RoomLib.Dao_Interface.TaskDao;
import com.example.esp8266.Library.RoomLib.Dao_Interface.TaskDetailDao;
import com.example.esp8266.Library.RoomLib.Dao_Interface.TaskGroupDao;
import com.example.esp8266.Library.RoomLib.Task;
import com.example.esp8266.Library.RoomLib.TaskDetail;
import com.example.esp8266.Library.RoomLib.TaskGroup;
import com.example.esp8266.Library.RoomLib.TaskGroupAdapter;
import com.example.esp8266.Library.RoomLib.VerticalSpaceItemDecoration;
import com.example.esp8266.R;
import com.example.esp8266.TcpService.Tcp_Connect;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


public class TaskRun_Fragment extends Fragment implements View.OnClickListener {

    private View root;
    private String back_info;
    private Fragment_CallBack callback;
    private Tcp_Connect tcpConnectService;
    private boolean isBound = false;
    private TaskGroupDao taskGroupDao;
    private TaskDao taskDao;
    private TaskDetailDao taskDetailDao;
    private RecyclerView recyclerView;
    private TaskGroupAdapter adapter;
    private List<TaskGroup> taskGroups;
    private AppDatabase database;

    /** 通过绑定（bind机制）连接到 Service*/
    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Tcp_Connect.TcpBinder binder = (Tcp_Connect.TcpBinder) service;
            tcpConnectService = binder.getService();
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };

    /**创立Service的服务连接*/
    /*
    @Override
    public void onStart() {
        super.onStart();
        Intent intent = new Intent(getActivity(), Tcp_Connect.class);
        requireActivity().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null) {
            // String target_device = args.getString("target_device", ""); // 目标控制设备
            back_info = args.getString("back_info", "MainControlFragment"); // 返回上一层标识
        }

        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("previous_page", back_info);
            editor.apply();
        } else {
            Log.e("Fragment", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }

    }

    /**创建Fragment回调函数*/
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof Fragment_CallBack) {
            callback = (Fragment_CallBack) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement Fragment_CallBack");
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.task_run_fragment, container, false);


        // 获取数据库实例
        database = ESP8266_APP.getInstance().getDatabase();
        taskGroupDao = database.taskGroupDao();
        taskDetailDao = database.taskDetailDao();
        taskDao = database.taskDao();

        // 初始化RecyclerView
        recyclerView = root.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));

        // 设置竖直间隔距离，比如16dp
        int spaceHeight = getResources().getDimensionPixelSize(R.dimen.recycler_view_item_space);
        recyclerView.addItemDecoration(new VerticalSpaceItemDecoration(spaceHeight));

        taskGroups = new ArrayList<>();
        adapter = new TaskGroupAdapter(taskGroups, requireContext());
        recyclerView.setAdapter(adapter);

        // 设置点击监听器
        adapter.setOnTaskGroupEditListener(taskGroup -> {
            Bundle args = new Bundle();
            args.putString("back_info", "TaskRun_Fragment");
            args.putString("task_groupName", taskGroup.groupName); // 传递任务组名称
            args.putInt("task_groupId", taskGroup.id); // 传递任务组ID

            // 处理点击事件，切换到 TaskList_Fragment 并传递任务组ID
            TaskList_Fragment taskListFragment = new TaskList_Fragment();
            taskListFragment.setArguments(args);
            replaceFragment(taskListFragment);
        });

        // 设置新建任务组按钮监听器
        adapter.setOnTaskGroupCreateListener(this::showCreateTaskGroupDialog);

        // 设置运行任务组按钮监听器
        adapter.setOnTaskGroupRunListener(taskGroup -> {
            // 运行任务组逻辑
            new Thread(() -> {
                StringBuilder dataBuilder = new StringBuilder();
                dataBuilder.append("TaskGroup: ").append(taskGroup.groupName).append("\n");
                List<Task> tasks = taskDao.getTasksByGroupId(taskGroup.id);
                for (Task task : tasks) {
                    dataBuilder.append("    Task: ").append(task.taskName).append("\n");
                    List<TaskDetail> taskDetails = taskDetailDao.getTaskDetailsByTaskId(task.id);
                    for (TaskDetail taskDetail : taskDetails) {
                        dataBuilder.append("        Detail: ").append(taskDetail.command)
                                .append(", Criteria: ").append(taskDetail.criteria)
                                .append("\n");
                    }
                }
                String data = dataBuilder.toString();

                // 在主线程中处理结果并调用 sendMessageToActivity 方法
                requireActivity().runOnUiThread(() -> {
                    sendMessageToActivity(data);
                });
            }).start();
        });

        // 设置删除任务组按钮监听器
        adapter.setOnTaskGroupDeleteListener(this::showDeleteTaskGroupDialog);

        // 加载任务组数据
        loadTaskGroups();

        return root;
    }

    /**加载任务组列表*/
    @SuppressLint("NotifyDataSetChanged")
    private void loadTaskGroups() {
        new Thread(() -> {
            List<TaskGroup> loadedTaskGroups = taskGroupDao.getAllTaskGroups();
            requireActivity().runOnUiThread(() -> {
                taskGroups.clear();
                taskGroups.addAll(loadedTaskGroups);
                adapter.notifyDataSetChanged();
            });
        }).start();
    }


    /**新建任务组逻辑*/
    private void showCreateTaskGroupDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("新建任务组");

        // 设置对话框的输入框
        final EditText input = new EditText(getContext());
        builder.setView(input);

        // 设置 "取消" 按钮
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        // 设置 "确认" 按钮
        builder.setPositiveButton("确认", (dialog, which) -> {
            String taskGroupName = input.getText().toString();
            if (TextUtils.isEmpty(taskGroupName)) {
                taskGroupName = "Group " + System.currentTimeMillis();
            }
            createNewTaskGroup(taskGroupName);
        });

        builder.show();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void createNewTaskGroup(String groupName) {
        new Thread(() -> {
            // 创建新的任务组
            TaskGroup newTaskGroup = new TaskGroup(groupName);
            database.taskGroupDao().insert(newTaskGroup);

            // 刷新任务组列表
            requireActivity().runOnUiThread(() -> {
                taskGroups.add(newTaskGroup);
                adapter.notifyDataSetChanged();
                Toast.makeText(getContext(), "新任务组创建成功: " + groupName, Toast.LENGTH_SHORT).show();
            });
        }).start();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void showDeleteTaskGroupDialog(TaskGroup taskGroup) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("删除任务组");
        builder.setMessage("确定要删除任务组吗？该操作将会删除所有相关任务。");

        // 设置 "取消" 按钮
        builder.setNegativeButton("取消", (dialog, which) -> {
            dialog.cancel();
            Toast.makeText(getContext(), "取消删除", Toast.LENGTH_SHORT).show();
        });

        // 设置 "删除" 按钮
        builder.setPositiveButton("删除", (dialog, which) -> {
            new Thread(() -> {
                taskDetailDao.deleteAll(); // 删除所有 TaskDetail 记录
                taskDao.deleteAll();       // 删除所有 Task 记录
                taskGroupDao.deleteAll();  // 删除所有 TaskGroup 记录

                // 刷新任务组列表
                requireActivity().runOnUiThread(() -> {
                    taskGroups.remove(taskGroup);
                    adapter.notifyDataSetChanged();
                    Toast.makeText(getContext(), "任务组已删除", Toast.LENGTH_SHORT).show();
                });
            }).start();
        });

        builder.show();
    }

    /**点击监听器*/
    @Override
    public void onClick(View v) {
        ;
    }

    /** 动态切换视图*/
    private void replaceFragment(Fragment fragment) {
        if (getActivity() != null) {
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.control_fragment_view, fragment);
            transaction.commit();
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        // 在离开 MainFragment 时
        if (isBound) {
            requireActivity().unbindService(serviceConnection);
            isBound = false;
        }
        callback = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 在 Fragment 生命周期结束时执行的操作
        callback = null;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        callback = null;
    }

    // 调用 callback 方法
    // 向 Activity 发数据
    private void sendMessageToActivity(String msg) {
        if (callback != null) {
            callback.sendMsgToActivity(msg);
        }
    }
}